﻿using AutoMapper;
using Consul;
using Durian.API.Application.Commands.Process;
using IMES.Common.Domain.DurianModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using System.Diagnostics;

namespace Durian.API.Application.Commands.Assembly
{
    public class AssemblyCreateHandler : IRequestHandler<AssemblyCreateCommand, Result>
    {
        private readonly IMapper mapper;
        private readonly ILogger<ProcessManagementCreateHandler> logger;
        private readonly IBaseRepositorys<ProcessManagement> processManagementRepository;
        private readonly IBaseRepositorys<SystemLogs> systemLogsRepository;
        private readonly IBaseRepositorys<Assemblies> assembliesRepository;
        private readonly IBaseRepositorys<OrderProducts> orderProductsRepository;

        public AssemblyCreateHandler(ILogger<ProcessManagementCreateHandler> logger, IMapper mapper, IBaseRepositorys<ProcessManagement> processManagementRepository, IBaseRepositorys<SystemLogs> systemLogsRepository, IBaseRepositorys<Assemblies> assembliesRepository, IBaseRepositorys<OrderProducts> orderProductsRepository)
        {
            this.logger = logger;
            this.mapper = mapper;
            this.processManagementRepository = processManagementRepository;
            this.systemLogsRepository = systemLogsRepository;
            this.assembliesRepository = assembliesRepository;
            this.orderProductsRepository = orderProductsRepository;
        }

        /// <summary>
        /// 装配工单添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(AssemblyCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result() { Code = (int)CodeEnum.add };
                Assemblies assemblies = mapper.Map<Assemblies>(request);
                var list = assembliesRepository.AddAsync(assemblies);
                result.Messege = "装配工单管理添加成功";
                result.Code = await list;
                logger.LogInformation("装配工单管理添加成功");
                SystemLogs system = new SystemLogs { SystemLogsId = request.SystemLogsId, LogeName = "装配工单管理添加成功", LogeTime = DateTime.Now };
                systemLogsRepository.AddAsync(system);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "装配工单管理添加失败");
                return new Result() { Code = (int)CodeEnum.error, Messege = "装配工单管理添加失败" };
            }
        }
    }
}
